﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using lib;
using lib.Twitter;
using myTwitter;

namespace one4all_UI
{
    public partial class startup : Form
    {
        delegate void SetTextCallback(string text);
        delegate void NewStatusAlertCallback(String msg);

        private Form frmStream;
        private Form frmAbout = new About();
        public myTwitter.myTwitter Twitter;
        public static bool loggedIn = false;


        public startup()
        {
            InitializeComponent();
            
            //Doubleclick should show list
            this.NotifyIcon1.DoubleClick += delegate
            {
                showStream();
            };

            //Dispose of the icon and clean settings if appropriate
            this.Closed += delegate
            {
                this.NotifyIcon1.Dispose();
                if (!Properties.Settings.Default.save)
                {
                    this.cleanSettings();
                }
                else
                {
                    this.storeSettings();
                }

            };

            this.Load += delegate
            {
                this.cAutostart.Checked = Properties.Settings.Default.autostart;
                this.cSave.Checked = Properties.Settings.Default.save;
                this.tUser.Text = Properties.Settings.Default.tUsername;
                this.tPass.Text = Properties.Settings.Default.tPassword;
            };

            //Activate if autostart is selected
            this.Shown += delegate
            {
                if (Properties.Settings.Default.autostart)
                {
                    this.activateOne4All();
                }
            };

            //Very important delegate. Handles Password encryption.
            this.tPass.Leave += delegate
            {
                if (tPass.Text != "")
                {
                    tPass.Text = tPass.Text.EncryptWithKey();
                }
            };
            //Not possible to get list until connected to twitter
            this.ctxTraySyna.Enabled = false;
        }

        //OnLoad
        private void startup_Load(object sender, EventArgs e)
        {
            try
            {
                if (lib.Settings.debug)
                {
                    this.machinename.Text = System.Environment.MachineName;
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        #region settings
        //Store settings while running app. 
        private void storeSettings()
        {
            Properties.Settings.Default.autostart = this.cAutostart.Checked;
            Properties.Settings.Default.save = this.cSave.Checked;
            Properties.Settings.Default.tUsername = this.tUser.Text;
            Properties.Settings.Default.tPassword = this.tPass.Text;
            Properties.Settings.Default.Save();
        }

        //Clean settings if not to be saved
        public void cleanSettings()
        {
            //Clean settings
            Properties.Settings.Default.autostart = false;
            Properties.Settings.Default.save = false;
            Properties.Settings.Default.tUsername = "";
            Properties.Settings.Default.tPassword = "";
            Properties.Settings.Default.Save();
        }

        #endregion settings

        #region activation
        //Activate the client
        public void activateOne4All()
        {
            storeSettings();
            
            //Test Twitter authentication if activated
            if ((Properties.Settings.Default.tUsername != "") && (Properties.Settings.Default.tPassword!=""))
            {
                Debug.WriteLine("Username: " + Properties.Settings.Default.tUsername);
                Twitter = new myTwitter.myTwitter(Properties.Settings.Default.tUsername, Properties.Settings.Default.tPassword.DecryptWithKey());
                this.Twitter.newStatus += delegate
                {
                    NewStatusAlert("New Tweet!");
                    Debug.WriteLine("Startup newStatus delegate");
                };

                BackgroundWorker bgw = new BackgroundWorker();
                Thread th =  new Thread(new ThreadStart(tLoopLogin));
                bgw.DoWork += delegate{
                        th.IsBackground = true;
                        th.Start();
                        loggedIn = Twitter.authUser();
                };
                bgw.RunWorkerCompleted += delegate{
                        Debug.WriteLine("Thread for looping text on login button killed:");
                        th.Abort();
                        if (loggedIn){
                            loginSuccess();
                        }
                        else { 
                            loginFailed(); 
                        }
                };
                bgw.RunWorkerAsync();

             }

                    

        }

        private void loginFailed()
        {
            MessageBox.Show(this, "Wrong username or password. ", "Authentication error");
            Twitter = null;
        }

        private void loginSuccess()
        {
            //Clean DB if different user
            if (Properties.Settings.Default.tUsername != Properties.Settings.Default.LastUser)
            {
                TwitterLinq.ResetDB();
                Debug.WriteLine("DB cleared because a new user logged in");
            }
            //Set LastUser attribute
            Properties.Settings.Default.LastUser = this.tUser.Text;

            //Initialize the listform
            frmStream = new o4aStream(this.Twitter);
            this.NotifyIcon1.ShowBalloonTip(1500, "One4All",
                    "The program is running in the background.",
                    ToolTipIcon.Info);
            ctxTrayShowHide.Text = "&Settings";
            this.ctxTraySyna.Enabled = true;
            this.Hide();
            this.activate.Text = "Activate";
            this.activate.Enabled = false;
            this.ctxLogout.Visible = true;
            this.ctxTraySyna.Visible = true;
        }



        //Loop login button text
        private void tLoopLogin()
        {
            String[] ext = new String[] { ".", "..", "..." };
            int counter = 0;
            while (true)
            {
                SetLoginText("Logging in" + ext[counter % 3]);
                counter++;
                Thread.Sleep(300);
            }
        }

        #endregion activation

        #region childrenFormShow
        //Show the about form
        private void showAbout()
        {
            if (!frmAbout.Visible)
            {
                frmAbout = new About();
                frmAbout.ShowDialog();

            }
        }

        //Show the list
        private void showStream()
        {
            if (frmStream != null)
            {
                if (!frmStream.Visible)
                {
                    frmStream.ShowDialog();

                }
                else
                {
                    frmStream.Select();
                }
            }
        }

        #endregion childrenFormShow

        #region ctxTrayMenus

        //ctxTraySettings: show and hide settings
        private void ctxTraySettings_Click(object sender, EventArgs e)
        {
            if(this.Visible){
                this.Hide();
            }
            else{
                this.Show();
            }
        }

        //ctxTrayAbout: Show about 
        private void ctxTrayAbout_Click(object sender, EventArgs e)
        {
            showAbout();
        }

        //ctxTrayShowHide: Show and hide tweet list
        private void ctxTrayShowHide_Click(object sender, EventArgs e)
        {
            if (Twitter != null)
            {
                showStream();
            }
        }


        //Logout menuitem
        private void ctxTrayLogout_Click(object sender, EventArgs e)
        {
            this.frmStream.Close();
            this.Show();
            this.activate.Enabled = true;
            this.ctxLogout.Visible = false;
            this.ctxTraySyna.Visible = false;
            this.Twitter = null;
            this.frmStream.Dispose();

        }


        //ctxTrayExit: Exit the client
        private void ctxTrayExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion ctxTrayMenus

        #region buttonsClicked

        //Activate the client
        private void activate_Click(object sender, EventArgs e)
        {
            this.activateOne4All();
        }

        //Exit the client
        private void quit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Show the about form when clicked
        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            showAbout();
        }

        #endregion buttonsClicked

        #region threadSafe
        //Thread safe function to set the Login Button text
        private void SetLoginText(string text)
        {
            if (this.activate.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetLoginText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.activate.Text = text;
            }
        }

        //Thread save method to handle newstatus alerts
        private void NewStatusAlert(String msg)
        {
            if (this.InvokeRequired)
            {
                NewStatusAlertCallback d = new NewStatusAlertCallback(NewStatusAlert);
                this.Invoke(d, new object[] { msg });
            }
            else
            {
                if (!frmStream.Focused)
                {
                    this.NotifyIcon1.ShowBalloonTip(1500, "One4All",
                            msg,
                            ToolTipIcon.Info);
                }
            }
        }

        #endregion threadSafe
    }
}
